#!/bin/bash
set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function download_kunpeng-gcc() {
  echo "# kunpeng-gcc编译器正在下载"
  wget -t 40 -c -P "$1" https://mirrors.huaweicloud.com/kunpeng/archive/compiler/kunpeng_gcc/gcc-10.3.1-2022.06-aarch64-linux.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# kunpeng-gcc编译器已经下载成功\033[0m"
  else
    echo -e "\033[31m# kunpeng-gcc编译器下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_kunpeng-gcc() {
  echo "# kunpeng-gcc编译器正在安装"
  tar xf "$1"/gcc-10.3.1-2022.06-aarch64-linux.tar.gz -C "$1" && rm -rf "$1"/gcc-10.3.1-2022.06-aarch64-linux.tar.gz
  mkdir -p "$2"/kunpeng-gcc-10.3.1 && cp -r "$1"/gcc-10.3.1-2022.06-aarch64-linux/* "$2"/kunpeng-gcc-10.3.1/
  echo -e "\033[1;32;1m# kunpeng-gcc编译器已经安装完毕\033[0m"
}

function install_development() {
  sudo yum install -y wget git tar libatomic environment-modules
  source /etc/profile
}

function write_kunpeng-gcc_module() {
  cat >"$1/kunpeng-gcc-10.3.1/kunpeng-gcc_modulefiles" <<EOF
#%Module1.0
conflict kunpeng-gcc
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set KUNPENG_GCC \$pwd
setenv KUNPENG_GCC \$KUNPENG_GCC
prepend-path PATH \$KUNPENG_GCC/bin
prepend-path INCLUDE \$KUNPENG_GCC/include
prepend-path LD_LIBRARY_PATH \$KUNPENG_GCC/lib64
prepend-path MODULEPATH \$KUNPENG_GCC
EOF
}

function main() {
  is_check_build_install_directory "$1" "$2" "kunpeng-gcc-10.3.1.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_kunpeng-gcc "$1"
  install_kunpeng-gcc "$1" "$2"
 write_kunpeng-gcc_module "$2"
  rm -rf "$1"/gcc-10.3.1-2022.06-aarch64-linux
}

main "$@"
